<template>
  <el-container style="height: 100vh; background-color: #f8f9fa; overflow: hidden">
    <!-- 左侧导航栏 -->
    <el-aside width="220px" style="background-color: #fff; box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05)">
      <Sidebar />
    </el-aside>

    <!-- 右侧内容容器（包含滚动） -->
    <el-container style="height: 100vh; overflow-y: auto">
      <!-- 页面头部 -->
      <el-header
          style="height: 64px;
              background: #fff;
              border-bottom: 1px solid #e8ebee;
              padding: 0 24px;
              position: sticky;
              top: 0;
              z-index: 1000">
        <div style="display: flex; align-items: center; height: 100%">
          <el-avatar
              :size="42"
              src="https://tse2-mm.cn.bing.net/th/id/OIP-C.KXyKVyQgsaqsg7dRS3bGmgHaGN?w=212&h=180&c=7&r=0&o=5&dpr=1.5&pid=1.7"
              style="margin-right: 12px"
          />
          <div>
            <h2 style="margin: 0; font-size: 18px; color: #1a1a1a">张三</h2>
            <p style="margin: 0; font-size: 13px; color: #909399">牛马大学生</p>
          </div>
        </div>
      </el-header>

      <!-- 页面主体 -->
      <el-main style="padding: 40px 15%; background: #f8f9fa">


        <!-- 帖子列表 -->
        <div class="post-list" style="margin-top: 40px">
          <div
              v-for="post in posts"
              :key="post.postId"
              class="post-card"
              style="transition: all 0.2s ease">
            <!-- 帖子头部 -->
            <div class="post-header">
              <div style="display: flex; justify-content: space-between; align-items: flex-start">
                <div class="user-info">
                  <h3 style="margin: 0;
                            color: #2c3e50;
                            font-size: 16px;
                            font-weight: 600;
                            text-align: left">
                    发帖人: {{ post.teacherName }}
                  </h3>
                  <div style="display: flex;
                              gap: 20px;
                              margin-top: 12px;
                              flex-wrap: wrap">
                    <div class="meta-item">
                      <span class="meta-label">邮箱：</span>
                      <span class="meta-value">{{ post.teacherEmail }}</span>
                    </div>
                    <div class="meta-item">
                      <span class="meta-label">发布时间：</span>
                      <span class="meta-value">{{ formatDate(post.postTime) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 帖子内容 -->
            <div class="post-content">
              <div class="content-label" style="font-size: 13px;
                                              color: #909399;
                                              margin-bottom: 8px;
                                              text-align: left">
                内容详情
              </div>
              <div class="content-text" style="font-size: 15px;
                                              color: #303133;
                                              line-height: 1.8;
                                              white-space: pre-wrap;
                                              font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                                              text-align: left">
                {{ post.content }}
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="post-actions">
              <div style="display: flex;
                        gap: 12px;
                        justify-content: flex-end;
                        padding-top: 20px;
                        border-top: 1px solid #ebeef5;
                        margin-top: 20px">
                <el-button
                    type="info"
                    size="small"
                    @click="viewComments(post.postId)"
                    style="border-radius: 18px;
                        padding: 8px 20px;
                        font-size: 13px">
                  <el-icon><ChatDotRound /></el-icon>
                  查看评论
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 评论弹窗 -->
        <el-dialog
            v-model="commentDialogVisible"
            title="评论"
            width="80%"
            :before-close="handleClose">
          <div v-if="currentPostComments && currentPostComments.length > 0">
            <div
                v-for="comment in currentPostComments"
                :key="comment.commentId"
                style="margin-bottom: 20px; padding-bottom: 10px; border-bottom: 1px solid #ebeef5">
              <div style="display: flex; justify-content: space-between; align-items: center">
                <div>
                  <strong>{{ comment.studentName }}</strong>
                  <span style="color: #909399; margin-left: 10px">{{ formatDate(comment.commentTime) }}</span>
                </div>
              </div>
              <div style="margin-top: 8px; text-align: left">
                <div style="font-size: 13px; color: #909399; margin-bottom: 4px">评论内容</div>
                <div>{{ comment.content }}</div>
              </div>
            </div>
          </div>
          <div v-else>
            <p style="color: #909399; text-align: center">暂无评论</p>
          </div>
                    <template #footer>
                      <div style="display: flex; gap: 10px">
                        <el-input
                            v-model="newComment"
                            placeholder="添加评论..."
                            style="flex: 1"
                            @keyup.enter="addComment"
                        />
                        <el-button
                            type="primary"
                            @click="addComment"
                            style="border-radius: 20px"
                        >
                          发布
                        </el-button>
                      </div>
                    </template>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ChatDotRound } from '@element-plus/icons-vue'
import axios from 'axios'
import Sidebar from "@/views/Sidebar.vue"

export default {
  components: {
    Sidebar,
    ChatDotRound
  },
  data() {
    return {
      newPostContent: '',
      posts: [],
      loading: false,
      currentTeacher: {
        teacherId: 1,
        teacherName: '熊老师',
        teacherEmail: 'xiong@example.com'
      },
      commentDialogVisible: false,
      currentPostId: null,
      currentPostComments: [],
      newComment: ''
    }
  },
  mounted() {
    this.fetchPosts()
  },
  methods: {
    async fetchPosts() {
      try {
        const response = await axios.get('http://localhost:80/postsWithTeachers')
        if (response.data.code === 0) {
          this.posts = response.data.data.sort((a, b) =>
              new Date(b.postTime) - new Date(a.postTime)
          )
        }
      } catch (error) {
        ElMessage.error('获取帖子失败')
      }
    },
    async addPost() {
      if (!this.newPostContent.trim()) {
        ElMessage.warning('请输入帖子内容')
        return
      }

      this.loading = true
      try {
        await axios.post('http://localhost:80/posts', null, {
          params: {
            Content: this.newPostContent,
          }
        })
        ElMessage.success('发布成功')
        this.newPostContent = ''
        this.fetchPosts()
      } catch (error) {
        ElMessage.error('发布失败')
      } finally {
        this.loading = false
      }
    },
    async viewComments(postId) {
      this.currentPostId = postId
      try {
        const response = await axios.get(`http://localhost:80/comments/post/${postId}`)
        if (response.data.code === 0) {
          this.currentPostComments = response.data.data
          this.commentDialogVisible = true
        } else {
          ElMessage.error(response.data.message || '获取评论失败')
          this.currentPostComments = []
        }
      } catch (error) {
        ElMessage.error('获取评论失败')
        this.currentPostComments = []
      }
    },
    async addComment() {
      if (!this.newComment.trim()) {
        ElMessage.warning('请输入评论内容')
        return
      }

      try {
        await axios.post('http://localhost:80/comments',
            {
          post_id: this.currentPostId,
          content: this.newComment
        })
        ElMessage.success('评论发布成功')
        this.newComment = ''
        await this.fetchComments()
      } catch (error) {
        ElMessage.error('评论发布失败')
      }
    },
    async fetchComments() {
      try {
        const response = await axios.get(`http://localhost:80/comments/post/${this.currentPostId}`)
        if (response.data.code === 0) {
          this.currentPostComments = response.data.data
        }
      } catch (error) {
        ElMessage.error('获取评论失败')
      }
    },
    confirmDeletePost(postId) {
      ElMessageBox.confirm('确定要删除这个帖子吗？', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deletePost(postId)
      })
    },
    async deletePost(postId) {
      try {
        await axios.delete(`http://localhost:80/posts/${postId}`)
        ElMessage.success('删除成功')
        this.posts = this.posts.filter(post => post.postId !== postId)
      } catch (error) {
        ElMessage.error('删除失败')
      }
    },
    formatDate(dateString) {
      const date = new Date(dateString)
      return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },
    handleClose(done) {
      this.currentPostId = null
      this.currentPostComments = []
      this.newComment = ''
      done()
    }
  }
}
</script>

<style scoped>
/* 布局优化 */
.el-container {
  overflow: hidden;
}

.el-main {
  min-height: calc(100vh - 64px);
  background: #f8f9fa !important;
  padding: 40px 15% !important;
}

/* 发帖编辑器 */
.post-editor {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  margin-bottom: 40px;
}

/* 帖子卡片 */
.post-card {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

/* 元信息样式 */
.meta-item {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: #606266;
}

.meta-label {
  color: #909399;
  margin-right: 6px;
}

.meta-value {
  color: #606266;
}

/* 发帖人信息和内容详情左对齐 */
.user-info {
  text-align: left;
}

.content-label {
  text-align: left;
}

.content-text {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .el-main {
    padding: 40px 10% !important;
  }
}

@media (max-width: 768px) {
  .el-main {
    padding: 24px 5% !important;
  }

  .post-card {
    padding: 16px;
  }

  .post-actions .el-button {
    width: 100%;
    margin-top: 8px;
  }

  .meta-item {
    flex-wrap: wrap;
    gap: 4px;
  }
}

@media (max-width: 480px) {
  .el-header {
    padding: 0 16px !important;
  }

  .el-main {
    padding: 20px 16px !important;
  }

  .post-editor {
    margin-bottom: 24px;
  }
}
</style>
